<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>父子组件的通讯-子传父(自定义事件)</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>

  <body>
    <div id="app">
      <childcpn @increment="changeTotal" @decrement="changeTotal"></childcpn>
      <h2>点击次数：{{total}}</h2>
    </div>
    <template id="childcpn">
      <div>
        <!-- 在父组件中，通过v-on来监听子组件事件。 -->
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
      </div>
    </template>
    <script>
      //创建Vue实例,得到 ViewModel
      var app = new Vue({
        el: "#app",
        data: {
          total: 0,
        },
        methods: {
          changeTotal(counter) {
            this.total = counter;
          },
        },
        components: {
          childcpn: {
            template: "#childcpn",
            data() {
              return {
                counter: 0,
              };
            },
            methods: {
              increment() {
                this.counter++;
                // 在子组件中，通过$emit()来触发事件
                this.$emit("increment", this.counter);
              },
              decrement() {
                this.counter--;
                this.$emit("decrement", this.counter);
              },
            },
          },
        },
      });
    </script>
  </body>
</html>
